#include "EPhControllerManager.h"
#include "EPhScene.h"
#include "EPhAllocator.h"
#include "eCPP.h"

namespace engine
{

//------------------------------------------------------------
EPhControllerManager::EPhControllerManager() :
m_pNxControllerManager( NULL )
{
  m_pNxControllerManager = NxCreateControllerManager( &g_PhAllocator );
  cASSERT( m_pNxControllerManager != NULL );
}

//------------------------------------------------------------
EPhControllerManager::~EPhControllerManager()
{
  if( m_pNxControllerManager != NULL )
  {
    m_pNxControllerManager->purgeControllers();
    NxReleaseControllerManager( m_pNxControllerManager );
    for( vector<EPhController*>::iterator it=m_vControllers.begin();
      it != m_vControllers.end(); it++ )
      delete *it;
    m_vControllers.clear();
  }
  else
  {
    cASSERT( m_vControllers.size() == 0 );
  }
}

//------------------------------------------------------------
void EPhControllerManager::updateControllers()
{
  cASSERT( m_pNxControllerManager != NULL );
  m_pNxControllerManager->updateControllers();
}

//------------------------------------------------------------
EPhController* EPhControllerManager::createController(EPhScene& scene, const EPhControllerDesc& desc)
{
  cASSERT( m_pNxControllerManager != NULL );
  NxController* pNxController = m_pNxControllerManager->createController(scene.getNxScenePtr(), desc.getNxControllerDesc());
  cASSERT( pNxController != NULL );
  EPhController* pController = new EPhController( *pNxController );
  cASSERT( pController != NULL );
  if( pController == NULL ) 
    return NULL;
  m_vControllers.push_back( pController );

  return pController;
}

//------------------------------------------------------------
void EPhControllerManager::destroyController(EPhController& controller )
{
  cASSERT( m_pNxControllerManager != NULL );
  NxController* pController = controller.getNxControllerPtr();
  if( pController != NULL )
    m_pNxControllerManager->releaseController( *pController );
}

} // end namespace